<?php
namespace App\Common\Server\Api\Lib;

use App\Common as com;
use App as nameApp;

class ParamField extends nameApi\Base {

	/**
	 * @var array|null 格式：[ 'field' => 1 ]
	 */
	private ?array $fieldArrayIndex = null;

	/**
	 * $fieldArray的索引缓存
	 * @var array|null 格式：[ 'field' => 1 ]
	 */
	private ?array $fieldArrayIndexCache = null;

	public function __construct( array $fieldArray ) {
		$this->fieldArrayIndex = com\Lib\Fun\Array_::arrayFlip( $fieldArray, [
			'newValue' => 1,
		] );
		//
		parent::__construct();
	}

	/**
	 * 是否包含全部
	 * @return bool
	 */
	public function isAll(  ):bool {
		return isset( $this->fieldArrayIndex['all'] );
	}

	/**
	 * 是否存在指定字段名、父前缀、全部
	 * @param string $fieldName
	 * @return bool
	 */
	public function is( string $fieldName ):bool {
		if( $this->isAll() ){
			return true;
		}
		//
		$fieldArrayIndexCache = $this->getFieldArrayIndexCache();
		//
		return array_key_exists( $fieldName, $fieldArrayIndexCache );
		//
/*		if( isset( $this->fieldArrayIndex[ $fieldName ] ) ){
			return true;
		}
		// 匹配前缀
		$fieldNameExplodeArray = explode( '.', $fieldName );
		$fieldPrefix = ''; // 完整前缀
		foreach( $fieldNameExplodeArray as $fieldNameExplodeValue ){
			if( $fieldPrefix !== '' ){
				$fieldPrefix .= '.';
			}
			$fieldPrefix .= $fieldNameExplodeValue;
			//
			if( array_key_exists( $fieldPrefix, $this->fieldArrayIndex ) ){
				return true;
			}
		}
		//
		return false;*/
	}

	/**
	 * 是否含有指定前端的字段名或全部
	 * @param string $fieldPrefixName
	 * @return bool
	 */
	public function isOfFull( string $fieldPrefixName ):bool {
		if( $this->isAll() ){
			return true;
		}
		return array_key_exists( $fieldPrefixName, $this->fieldArrayIndex );
	}

	/**
	 * 是否含有指定前端的字段名或全部
	 * @param string $fieldPrefixName
	 * @return bool
	 */
	public function isPrefixMatch( string $fieldPrefixName ):bool {
		if( $this->isAll() ){
			return true;
		}
		//
		$fieldArrayIndexCache = $this->getFieldArrayIndexCache();
		//
		return array_key_exists( $fieldPrefixName, $fieldArrayIndexCache );
	}

	/**
	 * 获取fieldArray的索引缓存，如$fieldArrayIndex['a.b.c']将得[ 'a', 'a.b', 'a.b.c'  ]
	 * @return array
	 */
	private function getFieldArrayIndexCache(  ):array {
		if( $this->fieldArrayIndexCache === null ){
			$fieldArrayIndexCache = [];
			foreach( $this->fieldArrayIndex as $fieldKey => $fieldValue ){
				$fieldKeyArray = explode( '.', $fieldKey );
				$fieldPrefix = ''; // 完整前缀
				foreach( $fieldKeyArray as $fieldKeyValue ){
					if( $fieldPrefix !== '' ){
						$fieldPrefix .= '.';
					}
					//
					$fieldPrefix .= $fieldKeyValue;
					//
					$fieldArrayIndexCache[$fieldPrefix] = true;
				}
			}
			//
			$this->fieldArrayIndexCache = $fieldArrayIndexCache;
		}
		//
		return $this->fieldArrayIndexCache;
	}

	// ===============================
	//
	//
	// 下面为静态方法
	//
	//
	// ===============================

	public static function new( array $fieldArray ):self {
		return new static( $fieldArray );
	}

}
